<template>
    <div class="map-container">
      <div id="grid-map-container"></div>
<!--      <div class="info">
        <el-input id="tipinput"
                  v-model="mapSearch.key"
                  class="input-with tipinput"
                  placeholder=""
                  clearable
                  @keyup.native.enter="handleMapSearch"
        >
          <el-button
            slot="append"
            size="small"
            type="primary"
            icon="el-icon-search"
            @click="handleMapSearch"
          ></el-button>
        </el-input>
      </div>-->
      <div class="input-card" style="width: 120px; position: absolute;"
           >
        <el-button type="primary" plain @click="polyEditorOpen" style="margin-bottom: 5px">开始编辑</el-button>
        <el-button type="primary" plain @click="polyEditorClose" style="margin-bottom: 5px;margin-left: 0;">结束编辑</el-button>
        <el-button type="primary" plain @click="polyClear" style="margin-left: 0;">清空区域</el-button>
      </div>
    </div>
</template>

<script>

  const AMap = window.AMap;
  export default {
    name: 'Location',
    props: {
      lng: {
        type:[Number, String],
        default: 116.974954
      },
      lat: {
       type:[Number, String],
       default: 37.464339
      },
      searchShow: {
        type: Boolean,
        default: true
      },
      operationType:{
        type: Number,
        default:1
      },
      domains:{
        type:String
      }
    },
    data() {
      return {
        center: [this.lng,this.lat],
        zoom: 16,
        // 线条颜色
        strokeColor: '#176ffc',
        // 线条透明度
        strokeOpacity: 0.6,
        // 线条宽度
        strokeWeight: 1,
        // 填充颜色
        fillColor: '#1791fc',
        // 填充透明度
        fillOpacity: 0.4,
        path: [],
        map: undefined,
        polygon: undefined,
        // 地图右键菜单
        contextMenu: undefined,
        // 地图点击事件监听
        clickListener: undefined,
        // 输入提示组件id
        autoOptions: {
          input: 'tipinput'
        },
        // 地图输入提示插件
        mapAutoComplete: undefined,
        // 地图输入提示点击监听
        autoCompleteSelectListener: undefined,
        // 地图地点查询类
        placeSearch: undefined,
        // 圆点标识，用于显示网格区域顶点
        circleMarker: [],
        mapSearch: {
          key: '',
          city: '泉州'
        },
      };
    },
    watch: {
      defaultValue() {
        this.searchValue = this.defaultValue;
      },
      lng(){
        if(this.domains==undefined||this.domains==''){
          if(this.map){
            this.center=[this.lng,this.lat];
            this.map.setCenter(this.center);
          }
        }
      }
    },
    mounted() {
      // 初始化地图页面
      this.initMap();
    },
    beforeDestroy() {
      // 销毁地图
      this.map.destroy();
    },
    methods: {
      /** 二维数组转字符串 **/
      doubleDiaArray2Str(array) {
        let arrLen = array.length
        let row = '['
        for (let i = 0; i < arrLen; i++) {
          row += '['
          for (let j = 0; j < array[i].length; j++) {
            row += array[i][j]
            if (j < array[i].length - 1) {
              row += ','
            }
          }
          row += ']'
          if (i < arrLen - 1) {
            row += ','
          }
        }
        row += ']'
        return row
      },
      /** 字符串转二维数组 **/
      str2DoubleDiaArray(str) {
        if (str != undefined && str != null && str.length > 0) {
          return eval(str)
        }
      },
      mapClickCallback(e) {
        const coordinate = [e.lnglat.lng, e.lnglat.lat]
        this.path.push(coordinate)
        let pathTmp = []
        Object.assign(pathTmp, this.path)
        // 新增顶点
        this.addCircleMarker(e.lnglat.lng, e.lnglat.lat)
        this.addPolygon(pathTmp)
        this.$emit("getPolyData",this.doubleDiaArray2Str(this.path));
      },
      /** 初始化map **/
      initMap() {
        // if (!this.map) {
        this.center=[this.lng,this.lat];
        this.map = new AMap.Map('grid-map-container', {
          resizeEnable: true, //是否监控地图容器尺寸变化
          zoom: this.zoom, //初始化地图层级
          center: this.center //初始化地图层级
        })
        // }
        let that = this
        // 地图加载完成的回调
        this.map.on('complete', function() {
          if (that.operationType != 1) {
            // 编辑和查看时需要调用的操作，加载网格范围
            that.loadGridScope()
          }
        })
        /*      if (this.clickListener) {
                // 先解除绑定，防止重复绑定
                AMap.event.removeListener(this.clickListener)
              }*/

        if (this.operationType != 3) {
          // 新增和编辑时才绑定鼠标点击事件
          this.clickListener = AMap.event.addListener(this.map, 'click', function(e) {
            that.mapClickCallback(e)
          })
        }
        // this.initAutoCompletePlugin('泉州')
        // 初始化之后必须把提示控件的z-index设置高一点，否则会被modal遮盖
        // $('.amap-sug-result').attr('style', 'z-index:3000')
       /* if (!this.placeSearch) {
          // 构造地点查询类
          this.placeSearch = new AMap.PlaceSearch({
            pageSize: 1, // 单页显示结果条数
            pageIndex: 1 // 页码
          })
        }*/

      },
      polyEditorOpen() {
        this.polyEditor.open()
        if (this.clickListener) {
          // 编辑区域时，先解除绑定，防止点击事件重复
          AMap.event.removeListener(this.clickListener)
        }
      },
      polyEditorClose() {
        this.polyEditor.close()
        // 结束编辑时重新绑定鼠标点击事件
        let that = this
        this.clickListener = AMap.event.addListener(this.map, 'click', function(e) {
          that.mapClickCallback(e)
        })
      },
      /** 初始化输入提示控件，默认查询范围是全国 **/
      initAutoCompletePlugin(city) {
        // 先移除已经创建的监听
        if (this.autoCompleteSelectListener) {
          AMap.event.removeListener(this.autoCompleteSelectListener)
        }
        // 初始化输入提示控件
        this.mapAutoComplete = new AMap.Autocomplete({
          city: city,
          input: 'tipinput'
        })
        // 注册监听，当选中某条记录时会触发
        this.autoCompleteSelectListener = AMap.event.addListener(this.mapAutoComplete, 'select', this.mapOptionSelect)
      },
      mapOptionSelect(e) {
        this.mapSearch.key = e.poi.name
        this.mapSearch.city = e.poi.adcode
        this.handleMapSearch()
      },
      handleMapSearch() {
        let that = this
        if (this.placeSearch) {
          this.placeSearch.setCity(this.mapSearch.city)
          this.placeSearch.search(this.mapSearch.key, function(status, result) {
            if (result.poiList && result.poiList.pois && result.poiList.pois.length > 0) {
              if (that.map) {
                let point = result.poiList.pois[0].location
                that.map.setCenter([point.lng, point.lat])
                that.map.setZoom(17)
              }
            } else {
              that.msgError('未找到相应地点:' + this.mapSearch.key)
            }
          })
        }
      },
      polyClear(){
        let that = this;
        // 清空选择区域
        if (that.map && that.polygon) {
          that.map.remove(that.polygon)
        }
        that.polygon = undefined
        //清空编辑器
        if(that.polyEditor){
          that.polyEditorClose();
        }
        that.polyEditor = undefined
        that.path = []
        this.$emit("getPolyData",'');
        // 清空区域端点
        that.clearCircleMarker()
        that.showPolyEditor = false;
      },
      /** 创建右键菜单 **/
      initContextMenu() {
        this.contextMenu = new AMap.ContextMenu()
        let that = this
        this.contextMenu.addItem('清空选择区域', function() {
          // 清空选择区域
          if (that.map && that.polygon) {
            that.map.remove(that.polygon)
          }
          that.polygon = undefined
          //清空编辑器
          if(that.polyEditor){
            that.polyEditorClose();
          }
          that.polyEditor = undefined
          that.path = []
          this.$emit("getPolyData",'');
          // 清空区域端点
          that.clearCircleMarker()
          that.showPolyEditor = false;
        }, 0)
      },
      /** 在地图上加载网格范围 **/
      loadGridScope() {
        let that = this
        if (this.map && this.domains != undefined && this.domains.length > 0) {
          // 将网格区域显示在地图上
          this.path = this.str2DoubleDiaArray(this.domains)
          let pathTmp = []
          Object.assign(pathTmp, this.path)
          this.addPolygon(pathTmp)
          // 将地图中心移动到此处
          this.map.setCenter(this.path[0])
          // this.map.setZoom(15);
          this.map.setFitView([this.polygon])

          //编辑网格区域时，取消鼠标点击监听
          this.polygonEditorListener();
        }
      },

      //多边形编辑功能
      polygonEditorListener(){
        let that = this;
        if (this.operationType != 3) {
          this.showPolyEditor = true;
          this.polyEditor = new AMap.PolyEditor(this.map, this.polygon)

          this.polyEditor.on('addnode', function(event) {
            that.extractPolygonPath(event.target.w.path)
          })

          this.polyEditor.on('adjust', function(event) {
            that.extractPolygonPath(event.target.w.path)
          })

          this.polyEditor.on('removenode', function(event) {
            that.extractPolygonPath(event.target.w.path)
          })

          this.polyEditor.on('end', function(event) {
            // event.target 即为编辑后的多边形对象
            that.extractPolygonPath(event.target.w.path)
          })
        }
      },
      extractPolygonPath(pathArray) {
        let polygonPath = []
        pathArray.forEach(item => {
          let coordinate = [item.lng, item.lat]
          polygonPath.push(coordinate)
        })
        this.$emit("getPolyData",this.doubleDiaArray2Str(polygonPath));
      },
      addCircleMarker(lng, lat) {
        let circle = new AMap.CircleMarker({
          center: [lng, lat],
          radius: 2, //半径
          borderWeight: 1,
          strokeColor: this.fillColor,
          strokeOpacity: 1,
          strokeWeight: 1,
          fillOpacity: 1,
          // 线样式还支持 'dashed'
          fillColor: this.fillColor,
          zIndex: 50
        })
        if (this.map) {
          circle.setMap(this.map)
        }
        this.circleMarker.push(circle)
      },
      clearCircleMarker() {
        if (this.map) {
          this.circleMarker.forEach(item => {
            this.map.remove(item)
          })
        }
        this.circleMarker = []
      },
      clearPolygon(){
        var that=this;
        // 清空选择区域
        if (that.map && that.polygon) {
          that.map.remove(that.polygon)
        }
        that.polygon = undefined
        //清空编辑器
        if(that.polyEditor){
          that.polyEditorClose();
        }
        that.polyEditor = undefined
        that.path = []
        this.$emit("getPolyData",'')
        // 清空区域端点
        that.clearCircleMarker()
        that.showPolyEditor = false;
      },
      addPolygon(path) {
        if (this.polygon) {
          this.map.remove(this.polygon)
          this.polyEditor = undefined;
        }
        let polygontmp = new AMap.Polygon({
          path: path,
          strokeColor: this.strokeColor,
          strokeWeight: this.strokeWeight,
          strokeOpacity: this.strokeOpacity,
          fillOpacity: this.fillOpacity,
          fillColor: this.fillColor
        })
        let that = this
        if (this.contextMenu && this.operationType != 3) {
          polygontmp.on('rightclick', function(e) {
            that.contextMenu.open(that.map, e.lnglat)
          })
        }
        this.polygon = polygontmp
        this.map.add(polygontmp)
        this.polygonEditorListener();
      },
      /** 地图定位缩放初始化 **/
      reLocation() {
        if (this.map && this.operationType == 1) {
          if(this.polygon){
            this.map.setFitView([this.polygon])
          }else{
            this.map.setZoom(this.zoom)
          }
          this.map.setCenter(this.center)
        }
      },
    }
  }
</script>

<style scoped>
  #grid-map-container {
    height: 500px
  }

  ul.amap-menu-outer li {
    color: gray;
  }
  .map-container {

  }

  .map-container .info {
    position: absolute;
    top: 3rem;
    border-width: 0;
    opacity: 0.95;

  }

  .map-container .input-item {
    position: relative;
    display: flex;
    flex-wrap: wrap;
    align-items: center;
    width: 100%;
  }

  .map-container .input-item-prepend {
    margin-right: -1px;
  }

  .map-container .input-item-text {
    width: auto;
    padding: 0.4rem 0.7rem;
    display: inline-block;
    text-align-last: justify;
    align-items: center;
    margin-bottom: 0;
    font-size: 14px;
    font-weight: 400;
    line-height: 1.5;
    color: #495057;
    text-align: center;
    white-space: nowrap;
  }

  .map-container .tipinput {
    margin-top: 10px;
    margin-left: 10px;
    width: 350px;
  }

  .input-card {
    display: flex;
    flex-direction: column;
    min-width: 0;
    word-wrap: break-word;
    background-color: #fff;
    background-clip: border-box;
    width: 22rem;
    border-width: 0;
    border-radius: 0.5rem;
    box-shadow: 0 2px 6px 0 rgba(114, 124, 245, .5);
    position: fixed;
    top: 4rem;
    right: 1rem;
    -ms-flex: 1 1 auto;
    flex: 1 1 auto;
    padding: 0.75rem 0.75rem;
  }
</style>
